import { useEffect, useRef, useState } from 'react'
import AppConfig, { EmptyStatus, PageConfig } from '@/config'
import { fetchArticle, fetchBackend, fetchTags } from '@/api'
import AdminContribute from '@/components/AdminContribute'
import SearchBar from '@/components/SearchBar'
import { Pagination } from '@nextui-org/react'
import CardItem from '@/components/CardItem'
import Banner from '@/components/Banner'
import { keepScrollbar } from '@/utils'
import Layout from '@/layouts/default'
import { Col, Row } from 'antd'
import Router from 'next/router'
import Head from 'next/head'

type PageProps = {
  articles: any
  total?: number
  backendList: any
  tagList: any
}

const { title } = AppConfig

export default function CliPage({ articles, total, backendList, tagList }: PageProps) {
  const [articleList, setArticleList] = useState(articles)
  const feature = ['快速干净', '简单方便', '功能丰富']
  const pageRef = useRef<any>(1)
  const pageNum = total ? Math.ceil(total / PageConfig.base.limit) : 0

  useEffect(() => {
    if (articleList?.length) {
      setArticleList(articleList)
    }
  }, [articleList])

  useEffect(() => {
    keepScrollbar('scollbar-admin')
  }, [articles])

  // 分页处理
  const onPaginationChange = (page = 1) => {
    pageRef.current = page
    Router.push({ pathname: '/ui', query: { page } })
  }

  // 处理搜索
  const handleSearch = (values: any) => {
    Router.push({ pathname: '/ui', query: { ...values } })
  }

  return (
    <Layout>
      <Head>
        <title>{`Hooks - ${title}`}</title>
      </Head>
      <Banner title="实用的CLI集合" label="提交你的CLI" btnUrl="/post/edit?nav_id=4" className="app-cli-banner" feature={feature} />
      <AdminContribute />
      <div className="container app-page-admin my-5 relative">
        <SearchBar isShowTag={false} backendList={backendList} tagList={tagList} handleSearch={handleSearch} />
        <div className="app-admin-body">
          <Row gutter={30}>
            {articles?.length > 0 && articles.map((item: any) => {
              return (
                <Col key={item.id} className="app-admins-col" lg={6} sm={8} xs={24}>
                  <CardItem data={item} />
                </Col>
              )
            })}
          </Row>
          {!articles?.length && <div className="app-admin-empty">{EmptyStatus}</div>}
        </div>
        <div className="app-page-footer flex justify-between">
          <div />
          <Pagination initialPage={1} onChange={onPaginationChange} total={pageNum} />
        </div>
      </div>
    </Layout>
  )
}

export async function getServerSideProps({ query }: any) {
  const page = query?.page || 1
  const params = { navId: 4, ...PageConfig.base, page, ...query }

  const { rows: articles, page: { total } } = await fetchArticle({ params })
  const { rows: backendList } = await fetchBackend({ params: { type: 1 } })
  const { rows: tagList } = await fetchTags({ params: { type: 2 } })

  return { props: { articles, total, backendList, tagList } }
}
